<template>
  <el-popover trigger="click">
      <el-scrollbar style="height:260px;">
        <el-tree style="padding-right:20px;" ref="tree" :value="selectedOptions" @check-change="change" @node-click="nodeClick" :data="options" check-strictly show-checkbox node-key="columnId" :default-checked-keys="selectedOptions" :props="{ label: 'columnName', children: 'children' } ">
        </el-tree>
      </el-scrollbar>
      <el-button slot="reference" style="padding:10px 10px 10px 15px">
        {{values.substring(0,10)}}
        <i class="el-icon-arrow-down"></i>
      </el-button>
  </el-popover>
</template>
<style lang="scss" scoped>
.text {
  max-width: 80%;
  display: inline-block;
}
</style>

<script>
import { cateTree } from '@/utils/api'
export default {
  props: {
    value: String
  },
  data() {
    return {
      options: [],
      selectedOptions: this.value ? this.value.split(',') : []
    }
  },
  created() {
    this.getData()
  },
  computed: {
    values() {
      const val = []
      const fn = item => {
        item.forEach(item => {
          if (this.selectedOptions.indexOf(item.columnId.toString()) > -1) {
            return val.push(item.columnName)
          }
          if (item.children && item.children.length) {
            fn(item.children)
          }
        })
      }
      fn(this.options)
      return val.join(', ')
    }
  },
  methods: {
    change(n) {
      const m = this.$refs.tree.getCheckedKeys().join(',')
      this.$emit('input', m)
    },
    nodeClick(data, node) {
      this.$refs.tree.setChecked(node, !node.checked)
    },
    async getData() {
      this.pload = false
      const Datas = await cateTree()
      const fn = item => {
        item.forEach(item => {
          if (item.children.length) {
            fn(item.children)
          } else {
            delete item.children
          }
        })
      }
      fn(Datas)
      this.options = Datas
      this.pload = true
    }
  }
}
</script>